package br.com.projeto.web.vraptor.interceptors;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.view.Results;
import br.com.projeto.web.vraptor.controllers.MainController;

@Intercepts
public class NamingInterceptor implements Interceptor {

	private Result result;
	
	public NamingInterceptor(Result result)  {
		this.result = result;
	}
	
	public boolean accepts(ResourceMethod method) {
		return true;
	}

	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object instance) throws InterceptionException {
		
		try {
			if(!this.result.used()) {
				String controller;
				String action = method.getMethod().getName().toLowerCase();
				
				String resource = method.getResource().getType().getSimpleName().toLowerCase();
		
				if(resource.endsWith("controller"))
					controller = resource.substring(0, resource.lastIndexOf("controller")).toLowerCase();
				else 
					controller = resource.toLowerCase();
				this.result.include("controller", controller);
				this.result.include("action", action);
		
				stack.next(method, instance);
			}
		} catch (Exception e) {
			//wtf ??
			e.printStackTrace();
			this.result.use(Results.logic()).redirectTo(MainController.class).login();
		}

	}
}
